<template>
  <div class="table-view">
    <el-table
      ref="table"
      :border="tableList.border == false ? false : true"
      :data="tableList.tableInfomation"
      tooltip-effect="dark"
      style="width: 100%"
      :height="'calc(100% - 0px)'"
      :max-height="tableList.maxHeight"
      :lazy="tableList.lazy"
      size="mini"
      @selection-change="handleSelectionChange"
      :header-cell-style="{
        background: '#f1f3f8',
        color: '#000009',
        'font-size': '14px'
      }"
      :highlight-current-row="tableList.highlight"
      :row-class-name="tableRowClassName"
      @row-click="tableRowClick"
      :row-key="tableList.key"
      :default-expand-all="tableList.isDefaultExpandAll"
      :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
    >
      <el-table-column align="center" v-if="tableList.selectBox" type="selection" width="40"> </el-table-column>
      <el-table-column
        class="cell_index"
        align="center"
        v-if="tableList.selectIndex"
        type="index"
        label="序号"
        width="50"
      >
      </el-table-column>
      <template v-for="(item, i) in tableList.tableColumn">
        <el-table-column
          :align="item.align ? item.align : 'center'"
          :key="i"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :min-width="item.min"
          show-overflow-tooltip
          :sortable="item.sortable"
          v-if="item.isShowColumn"
        >
          <template slot-scope="scope">
            <span v-if="item.price">{{ "￥" + number_format(scope.row[item.prop], 2, ".", ",") }}</span>
            <div v-else-if="item.status">
              <span v-if="scope.row.status == '离线'" class="redColor">{{ scope.row[item.prop] }}</span>
              <span v-else-if="scope.row.status == '在线'" class="greenColor">{{ scope.row[item.prop] }}</span>
            </div>
            <span v-else-if="item.isTime">{{
              dateFormat("YYYY-mm-dd HH:MM:SS", scope.row[item.prop]) === "1900-01-01 00:06:26"
                ? "--"
                : dateFormat("YYYY-mm-dd HH:MM:SS", scope.row[item.prop])
            }}</span>
            <span
              v-else-if="item.isClick && scope.row[item.prop]"
              class="sel-name"
              @click="selCommonClick(scope.row)"
              >{{ scope.row[item.prop] }}</span
            >
            <span v-else-if="item.isFirst">{{ scope.row[item.prop] ? "是" : "否" }}</span>
            <span
              v-else-if="item.isCommonClick && scope.row[item.prop]"
              class="sel-name"
              @click="selCommonClick(scope.row)"
              >{{ scope.row[item.prop] }}</span
            >
            <div v-else-if="item.isProductName" class="product-view">
              <ul v-if="scope.row.products && scope.row.products.length > 0">
                <li v-for="(item, index) in scope.row.products" :key="index">
                  <div :class="scope.row.products.length === 1 ? 'name-view no-bottom' : 'name-view'">
                    {{ item.name }}
                  </div>
                </li>
              </ul>
              <div v-else class="no-product">{{ "--" }}</div>
            </div>
            <div v-else-if="item.isProductAmount" class="product-view">
              <ul v-if="scope.row.products && scope.row.products.length > 0">
                <li v-for="(item, index) in scope.row.products" :key="index">
                  <div :class="scope.row.products.length === 1 ? 'name-view no-bottom' : 'name-view'">
                    {{ item.amount }}
                  </div>
                </li>
              </ul>
              <div v-else class="no-product">{{ "--" }}</div>
            </div>
            <div v-else-if="item.isProductPrice" class="product-view">
              <ul v-if="scope.row.products && scope.row.products.length > 0">
                <li v-for="(item, index) in scope.row.products" :key="index">
                  <div :class="scope.row.products.length === 1 ? 'name-view no-bottom' : 'name-view'">
                    {{ item.price }}
                  </div>
                </li>
              </ul>
              <div v-else class="no-product">{{ "--" }}</div>
            </div>
            <div v-else-if="item.isProductTotal" class="product-view">
              <ul v-if="scope.row.products && scope.row.products.length > 0">
                <li v-for="(item, index) in scope.row.products" :key="index">
                  <div :class="scope.row.products.length === 1 ? 'name-view no-bottom' : 'name-view'">
                    {{ item.total }}
                  </div>
                </li>
              </ul>
              <div v-else class="no-product">{{ "--" }}</div>
            </div>
            <!-- 图片展示 -->
            <div v-else-if="item.showImage">
              <el-image style="width: 100px; height: 100px" :src="scope.row[item.prop]" fit="fill"> </el-image>
            </div>
            <!-- 开关 -->
            <div v-else-if="item.isSwitch">
              <el-switch v-model="scope.row.enable" @change="userTypeChange(scope.row)" />
            </div>

            <!-- 设备名称 -->
            <div v-else-if="item.deviceName" class="deviceName">
              <div class="deviceName_left">
                <img src="@/assets/images/Vector.png" alt="" />
              </div>
              <div class="deviceName_right">
                <p>{{ scope.row[item.prop] ? scope.row[item.prop] : "--" }}</p>
                <p>{{ scope.row.deviceCode ? scope.row.deviceCode : "--" }}</p>
              </div>
            </div>

            <!-- 绑定 -->
            <div v-else-if="item.bindingOperation" class="bindingOperation">
              <img src="@/assets/images/binding.png" alt="" />
              <span>解绑</span>
            </div>

            <span v-else-if="!item.showImage && !item.deviceName">{{
              scope.row[item.prop] ? scope.row[item.prop] : "--"
            }}</span>
          </template>
        </el-table-column>
      </template>
      <slot name="tableButton" />
      <div slot="empty">
        <el-empty description="暂无数据"></el-empty>
      </div>
    </el-table>
    <div class="overSpread1" v-show="iscolopen" @click="onMaskClick"></div>
    <div class="styleBtn" v-if="colOpenShow">
      <i @click="checkCol()" class="label">...</i>
      <el-checkbox-group v-model="showcol" v-show="iscolopen" class="checkbox-group" @change="selectCheckBoxList">
        <el-checkbox v-for="item in tableList.allcol" :label="item" :key="item">{{ item }} </el-checkbox>
      </el-checkbox-group>
    </div>
  </div>
</template>

<script>
export default {
  name: "TableCommonView",
  props: {
    tableList: {
      type: Object,
      default: () => {
        return {
          border: true,
          selectBox: false,
          selectIndex: false,
          tableInfomation: [], // 接口返回数据
          showcol: [],
          allcol: [],
          highlight: false,
          tableColumn: [
            // table表单
            { label: "", prop: "", min: 200, tooltip: true, enable: true }
          ]
        }
      }
    },
    showSummary: {
      type: Object,
      default: () => {
        return {
          show: false,
          sumProp: [],
          mergeNumber: 1,
          totalName: "本页总计"
        }
      }
    },
    // 选中的样式
    selectClassRow: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 是否可以配置列表 表头
    colOpenShow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      iscolopen: false,
      showcol: []
    }
  },
  watch: {
    "tableList.showcol": {
      handler(newVal) {
        this.showcol = newVal
      },
      immediate: true
    }
  },
  computed: {},
  methods: {
    onMaskClick() {
      this.iscolopen = false
    },
    checkCol() {
      this.iscolopen = !this.iscolopen
    },
    selectCheckBoxList(val) {
      this.$emit("selTableCol", val)
    },
    handleReserve(row) {
      return row._id ? row._id : row.id
    },
    handleSelectionChange(val) {
      this.$emit("getSelectArray", val)
    },
    // 行合并
    arraySpanMethod() {
      if (this.showSummary.show) {
        this.$nextTick(() => {
          if (this.$refs.table.$el) {
            var current = this.$refs.table.$el
              .querySelector(".el-table__footer-wrapper")
              .querySelector(".el-table__footer")
            var cell = current.rows[0].cells
            for (let i = 0; i < this.showSummary.mergeNumber; i++) {
              cell[i].style.display = "none"
            }
            cell[this.showSummary.mergeNumber].classList.remove("is-left")
            cell[this.showSummary.mergeNumber].colSpan = this.showSummary.mergeNumber.toString()
          }
        })
      }
    },
    // 金额合计
    getSummaries(param) {
      if (this.showSummary.show) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === this.showSummary.mergeNumber) {
            sums[index] = this.showSummary.totalName
          }
          const values = data.map((item) => Number(item[column.property]))
          if (this.showSummary.sumProp.includes(column.property)) {
            sums[index + 1] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index + 1]
            if (column.property === "taxUnitPrice") {
              let sumPrice = 0
              this.tableList.tableInfomation.map((item) => {
                item.products.map((val) => {
                  console.log(val.price)
                  sumPrice += parseFloat(val.price)
                })
              })
              console.log((sums[index + 1] = sumPrice))
              console.log(sumPrice)
            }
            if (column.property === "priceTax") {
              let sumPrice = 0
              this.tableList.tableInfomation.map((item) => {
                item.products.map((val) => {
                  console.log(val.price)
                  sumPrice += parseFloat(val.total)
                })
              })
              sums[index + 1] = sumPrice
            }
            if (column.property === "productAmount") {
              let sumPrice = 0
              this.tableList.tableInfomation.map((item) => {
                item.products.map((val) => {
                  console.log(val.price)
                  sumPrice += parseFloat(val.amount)
                })
              })
              sums[index + 1] = sumPrice
            }
          }
        })
        // console.log(sums)
        return sums
      }
    },
    // 数字换行为金额显示格式
    number_format(number, decimals, dec_point, thousands_sep) {
      decimals = 2 //这里默认设置保留两位小数，也可以注释这句采用传入的参数
      /*
       * 参数说明：
       * number：要格式化的数字
       * decimals：保留几位小数
       * dec_point：小数点符号
       * thousands_sep：千分位符号
       * */
      number = (number + "").replace(/[^0-9+-Ee.]/g, "")
      var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = typeof thousands_sep === "undefined" ? "," : thousands_sep,
        dec = typeof dec_point === "undefined" ? "." : dec_point
      var s = n.toString().split(".")
      var re = /(-?\d+)(\d{3})/
      while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2")
      }
      if ((s[1] || "").length < prec) {
        s[1] = s[1] || ""
        s[1] += new Array(prec - s[1].length + 1).join("0")
      } else {
        s[1] = s[1].substring(0, prec) //小数点位数超出长度时截取前面的位数
      }
      return s.join(dec)
    },
    // 时间显示
    dateFormat(fmt, date) {
      let ret = ""
      date = new Date(date)
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"))
        }
      }
      return fmt
    },
    // 公共详情
    selCommonClick(row) {
      this.$emit("selCommonClick", row)
    },
    // 单选行相关
    tableRowClassName({ row }) {
      if (Object.keys(this.selectClassRow).length > 0) {
        if (row.id == this.selectClassRow.id) {
          return "onSelect"
        }
      }
      this.$emit("tableRowClassName", row)
    },
    tableRowClick(row) {
      this.$emit("tableRowClick", row)
    },
    userTypeChange(row) {
      this.$emit("setSwitchType", row)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.table-view {
  // margin-top: 20px;
  // margin-right: 10px;
  // margin-bottom: 40px;
  position: relative;
  height: 100%;
  .blue {
    width: 70px;
    text-align: center;
    color: #fff;
    background-color: $color-primary;
    border-radius: 4px;
  }
  .sel-name {
    color: $color-primary;
    cursor: pointer;
  }
  .product-view {
    // background: #cc7d7d;
    margin-left: -10px;
    margin-right: -11px;
    li {
      height: 57px;
      line-height: 57px;
      .name-view {
        padding-left: 10px;
        border-bottom: 1px solid #141415;
      }
      .no-bottom {
        border-bottom: 0px;
      }
    }
    .no-product {
      height: 57px;
      line-height: 57px;
    }
  }
  .bindingOperation {
    width: 74px;
    height: 32px;
    border-radius: 3px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 5px 16px;
    gap: 8px;
    box-sizing: border-box;
    border: 1px solid #328eff;
    cursor: pointer;
    img {
      width: 18px;
      height: 18px;
    }
    span {
      font-size: 14px;
      line-height: 22px;
      color: #328eff;
    }
  }
  .deviceName {
    display: flex;
    justify-content: center;
    .deviceName_left {
      width: 55px;
      height: 48px;
      text-align: center;
      line-height: 58px;
      border-radius: 6px;
      background: #8291a9;
    }
    .deviceName_right {
      width: 110px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .el-tooltip {
        margin: 0 auto;
        width: 8em;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      p {
        width: 100%;
        margin: 0;
        text-align: left;
        padding-left: 10px;
        font-family: Poppins;
        width: 8em;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      p:nth-of-type(1) {
        font-size: 16px;
        font-weight: 500;
        line-height: 21px;
      }
      p:nth-of-type(2) {
        font-size: 14px;
        font-weight: 500;
        line-height: 21px;
        color: #8291a9;
      }
    }
  }
}
.redColor {
  color: #ff0404 !important;
}
.greenColor {
  color: #00ff9d;
}
::v-deep {
  .el-table {
    overflow: auto;
    border: none;

    th {
      background: #1f2935 !important;
      color: #fff !important;
      height: 55px;
    }
    tr {
      background-color: #1f2935;
      color: #fff;
    }
  }

  .el-table tbody tr:hover > td {
    background: #1f2935 !important;
  }
  .el-table__body .el-table__row.hover-row td {
    background-color: #1f2935 !important;
  }
  .el-table .success-row {
    background: #1f2935;
    /* background: #f5f7fa; */
  }
  .el-table::before {
    background: #141415;
  }
  .el-table {
    background: #141415 !important;
    overflow: auto;
    th {
      background: #1f2935 !important;
      color: #fff !important;

      .cell {
        color: #fff;
      }
    }
    .has-gutter {
      background: #1f2935 !important;
    }
    .el-table--border::after,
    .el-table--group::after,
    .el-table::before,
    .el-table__fixed-right::before {
      background-color: #ffffff00;
    }
    .el-table__header-wrapper {
      height: 55px;
    }
    .el-table__row {
      height: 55px;
    }
    .el-table__cell {
      border-color: #141415 !important;
    }
    .el-table td.el-table__cell,
    .el-table th.el-table__cell.is-leaf {
      border-bottom: 3px solid #141415 !important;
    }
    .el-table--border .el-table__cell,
    .el-table__body-wrapper .el-table--border.is-scrolling-left ~ .el-table__fixed {
      border-right: 3px solid #141415 !important;
    }
    .el-pagination.is-background .btn-next,
    .el-pagination.is-background .btn-prev,
    .el-pagination.is-background .el-pager li {
      background-color: #1f2935;
    }
  }

  .overSpread1 {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0);
    z-index: 10;
  }

  .styleBtn {
    position: absolute;
    width: 30px;
    height: 36px;
    // line-height: 26px;
    // background: #06c062;
    top: 0;
    right: 2px;
    z-index: 9999;
    .label {
      position: absolute;
      top: 6px;
      font-size: 20px;
      // line-height: 5px;
      cursor: pointer;
      color: #000;
      transform: rotate(-90deg);
    }
    .checkbox-group {
      width: 160px;
      height: 330px;
      overflow: auto;
      display: flex;
      flex-direction: column;
      line-height: 25px;
      background: #ffffff;
      border-radius: 16px;
      padding: 12px;
      position: absolute;
      right: 0;
      top: 30px;
      z-index: 99;
      box-shadow: 0 0 2px 2px #f8f8f8;
    }
  }
}
</style>
